<template>
  <el-dialog title="客户选择" v-if="showFlag" :visible.sync="showFlag" :close-on-click-modal="false" :modal=false
    width="80%" center>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="客户编码" prop="clientCode">
            <el-input v-model="queryParams.clientCode" placeholder="请输入客户编码" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="客户名称" prop="clientName">
            <el-input v-model="queryParams.clientName" placeholder="请输入客户名称" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="客户简称" prop="clientNick">
            <el-input v-model="queryParams.clientNick" placeholder="请输入客户简称" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="客户英文名称" prop="clientEn">
            <el-input v-model="queryParams.clientEn" placeholder="请输入客户英文名称" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否启用" prop="enableFlag">
            <el-select v-model="queryParams.enableFlag" placeholder="是否启用" clearable style="width: 215px">
              <el-option v-for="dict in dict.type.sys_yes_no" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            <el-button type="success" icon="el-icon-plus" size="mini" @click="handleQuickAdd">快速添加</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    <el-table highlight-current-row v-loading="loading" :data="clientList" @current-change="handleCurrent" @row-dblclick="handleRowDbClick">
      <el-table-column type="index" width="50">
          </el-table-column>
      <el-table-column label="客户编码" align="center" prop="clientCode" />
      <el-table-column label="客户名称" width="150px" align="center" prop="clientName" :show-overflow-tooltip="true" />
      <el-table-column label="客户简称" align="center" prop="clientNick" />
      <el-table-column label="客户类型" align="center" prop="clientType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_client_type" :value="scope.row.clientType" />
        </template>
      </el-table-column>
      <el-table-column label="客户电话" align="center" prop="tel" />
      <el-table-column label="联系人" align="center" prop="contact1" />
      <el-table-column label="联系人-电话" align="center" prop="contact1Tel" />
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="confirmSelect">确 定</el-button>
      <el-button @click="showFlag = false">取 消</el-button>
    </div>

    <!-- 快速添加客户对话框 -->
    <el-dialog title="快速添加客户" :visible.sync="quickAddOpen" width="800px" append-to-body>
      <el-form ref="quickAddForm" :model="quickAddForm" :rules="quickAddRules" label-width="120px">
        <el-row>
          <el-col :span="10">
            <el-form-item label="客户编码" prop="clientCode">
              <el-input v-model="quickAddForm.clientCode" placeholder="请输入客户编码" :readonly="autoGenFlag" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label-width="80">
              <el-switch v-model="autoGenFlag"
                  active-color="#13ce66"
                  active-text="自动生成"
                  @change="handleAutoGenChange(autoGenFlag)">
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="客户名称" prop="clientName">
              <el-input v-model="quickAddForm.clientName" placeholder="请输入客户名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户简称" prop="clientNick">
              <el-input v-model="quickAddForm.clientNick" placeholder="请输入客户简称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户类型" prop="clientType">
              <el-select v-model="quickAddForm.clientType" placeholder="请选择客户类型" style="width: 100%">
                <el-option
                  v-for="dict in dict.type.mes_client_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户电话" prop="tel">
              <el-input v-model="quickAddForm.tel" placeholder="请输入客户电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contact1">
              <el-input v-model="quickAddForm.contact1" placeholder="请输入联系人" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人电话" prop="contact1Tel">
              <el-input v-model="quickAddForm.contact1Tel" placeholder="请输入联系人电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否启用" prop="enableFlag">
              <el-radio-group v-model="quickAddForm.enableFlag">
                <el-radio
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="客户地址" prop="address">
              <el-input v-model="quickAddForm.address" type="textarea" placeholder="请输入客户地址" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitQuickAdd">确 定</el-button>
        <el-button @click="cancelQuickAdd">取 消</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import { listClient, getClient, delClient, addClient, updateClient } from "@/api/mes/md/client";
import { genCode } from "@/api/system/autocode/rule";
export default {
  name: "ClientSelectSingle",
  dicts: ['mes_client_type', 'sys_yes_no'],
  data() {
    return {
      showFlag: false,
      selectedClientId: undefined,
      selectedRow: undefined,
      // 遮罩层
      loading: true,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户表格数据
      clientList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 快速添加对话框
      quickAddOpen: false,
      // 快速添加表单
      quickAddForm: {
        clientCode: '',
        clientName: '',
        clientNick: '',
        clientType: '',
        tel: '',
        contact1: '',
        contact1Tel: '',
        address: '',
        enableFlag: 'Y'
      },
      // 快速添加表单验证规则
      quickAddRules: {
        clientCode: [
          { 
            required: true, 
            message: "客户编码不能为空", 
            trigger: "blur",
            validator: (rule, value, callback) => {
              if (this.autoGenFlag) {
                // 自动生成模式下，编码由系统生成，不需要验证
                callback();
              } else if (!value) {
                callback(new Error("客户编码不能为空"));
              } else {
                callback();
              }
            }
          }
        ],
        clientName: [
          { required: true, message: "客户名称不能为空", trigger: "blur" }
        ],
        clientType: [
          { required: true, message: "客户类型不能为空", trigger: "change" }
        ]
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        clientCode: null,
        clientName: null,
        clientNick: null,
        clientEn: null,
        clientDes: null,
        clientLogo: null,
        clientType: null,
        address: null,
        website: null,
        email: null,
        tel: null,
        contact1: null,
        contact1Tel: null,
        contact1Email: null,
        contact2: null,
        contact2Tel: null,
        contact2Email: null,
        creditCode: null,
        enableFlag: null,
      },
      // 自动生成客户编码开关
      autoGenFlag: false,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询客户列表 */
    getList() {
      this.loading = true;
      listClient(this.queryParams).then(response => {
        this.clientList = response.rows;
        this.total = response.total;
        this.selectedRow = undefined;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleCurrent(row) {
      if (row) {
        this.selectedRow = row;
      }
    },
    //行双击选中
    handleRowDbClick(row) {
      if (row) {
        this.selectedRow = row;
        this.$emit('onSelected', this.selectedRow);
        this.showFlag = false;
      }
    },
    // 单选选中数据
    handleRowChange(row) {
      if (row) {
        this.selectedRow = row;
      }
    },
    //确定选中
    confirmSelect() {
      if (this.selectedRow === undefined || this.selectedRow.clientId === '') {
        this.$notify({
          title: '提示',
          type: 'warning',
          message: '请至少选择一条数据!'
        });
        return;
      }
      this.$emit('onSelected', this.selectedRow);
      this.showFlag = false;
    },
    // 快速添加客户
    handleQuickAdd() {
      this.quickAddOpen = true;
      this.resetQuickAddForm();
    },
    // 重置快速添加表单
    resetQuickAddForm() {
      this.quickAddForm = {
        clientCode: '',
        clientName: '',
        clientNick: '',
        clientType: '',
        tel: '',
        contact1: '',
        contact1Tel: '',
        address: '',
        enableFlag: 'Y'
      };
      this.autoGenFlag = false; // 重置自动生成开关
      this.$nextTick(() => {
        this.$refs.quickAddForm && this.$refs.quickAddForm.clearValidate();
      });
    },
    // 提交快速添加
    submitQuickAdd() {
      this.$refs.quickAddForm.validate((valid) => {
        if (valid) {
          addClient(this.quickAddForm).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.quickAddOpen = false;
            this.getList();
            // 自动选中新添加的客户
            this.$nextTick(() => {
              const newClient = this.clientList.find(item => item.clientCode === this.quickAddForm.clientCode);
              if (newClient) {
                this.selectedRow = newClient;
                this.$notify({
                  title: '提示',
                  type: 'success',
                  message: `已自动选中新添加的客户：${newClient.clientName}`
                });
              }
            });
          }).catch(error => {
            this.$modal.msgError("新增失败：" + (error.message || "未知错误"));
          });
        }
      });
    },
    // 取消快速添加
    cancelQuickAdd() {
      this.quickAddOpen = false;
      this.resetQuickAddForm();
    },
         // 自动生成客户编码
     handleAutoGenChange(value) {
       if (value) {
         // 调用API生成客户编码
         genCode('CLIENT_CODE').then(response => {
           this.quickAddForm.clientCode = response;
         }).catch(error => {
           this.$modal.msgError("自动生成编码失败：" + (error.message || "未知错误"));
           this.autoGenFlag = false; // 失败时关闭开关
         });
       } else {
         this.quickAddForm.clientCode = ''; // 清空编码
       }
     }
  }
};
</script>
